package codeRandomThoughts.Test55跳跃游戏;

public class Solution {
    public boolean canJump(int[] nums) {
        int index = 0;

        while (nums[index] != 0) {
            //首先获取能跳到的范围
            int range = nums[index];
            int nextIndex = index;
            int maxDistance = index + range;

            //如果当前能跳到终点,返回true
            if (maxDistance + 1 >= nums.length) {
                return true;
            }

            for (int i = 1; i <= range; i++) {
                int jumpArea = index + i + nums[index + i];
                if (jumpArea > maxDistance) {
                    maxDistance = jumpArea;
                    nextIndex = index + i;
                }
            }

            //如果还是从本格出发能跳的最远,说明已经到不了了
            if (nextIndex == index) {
                return false;
            }

            index = nextIndex;
        }

        //如果只有一个元素,不用动就是终点
        return nums.length == 1;
    }
}
